import 'dart:async';
import 'dart:io';

import 'package:brightness/brightness.dart';
import 'package:camera/camera.dart';
import 'package:flutter_axrjc/datasource/network/bean/BackColorBean.dart';
import 'package:flutter_axrjc/util/ImageUtil.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';

typedef onCheckFinish = void Function(double detectionMaxValue,
    double detectionMinValue, double detectionAverageValue);

class LightUtil {
  CameraController? _controller;
  List<CameraDescription> cameras = [];
  CameraDescription? currentCamera;
  int elapsed = 0;
  double max = 0;
  double min = 1037;
  double currentAndroidData = 0;
  List<double> androidAverageLux = [];
  double androidMax = 0;
  double androidMin = 1037;
  List<double> cameraAverageLux = [];
  List<double> averageTemp = [];
  onCheckFinish? onFinish;

  bool _isPause = false;
  LightUtil() {
    availableCameras().then((value) {
      cameras.addAll(value);
      if (cameras.isNotEmpty) {
        currentCamera = cameras.first;
        if (currentCamera != null) {
          _controller = CameraController(currentCamera!, ResolutionPreset.low,
              imageFormatGroup: ImageFormatGroup.yuv420);
          _controller?.initialize();
        } else {
          EasyLoading.showToast("相机初始化失败");
        }
      }
    });
  }
  CameraController? get controller => _controller;
  Future<void> startCheck(
      {required void Function(BackColorBean backColor) onChecking}) async {
    reset();
    if (Platform.isAndroid) {
      GetBrightness.stream.listen((event) {
        if (!_isPause) {
          if (androidMax < event) {
            androidMax = event;
          }
          if (androidMin > event) {
            androidMin = event;
          }
          currentAndroidData = event;
        }
      });
      GetBrightness.startBrightnessStream();
    }
    _controller?.startImageStream((CameraImage cameraImage) async {
      if (!_isPause) {
        if (Platform.isAndroid) {
          androidAverageLux.add(currentAndroidData);
          onChecking.call(BackColorBean(
              lux: 0,
              // temp: bean.temp,
              temp: 0,
              androidLux: currentAndroidData));
        } else {
          LuxTemp bean = ImageUtil.calculateAverageTemperature(
              ImageUtil.convertYUV420ToImage(cameraImage));
          if (max < bean.lux) {
            max = bean.lux;
          }
          if (min > bean.lux) {
            min = bean.lux;
          }
          cameraAverageLux.add(bean.lux);
          averageTemp.add(bean.temp);
          onChecking.call(
              BackColorBean(lux: bean.lux, temp: bean.temp, androidLux: 0));
        }
      }
    });
  }

  void finish() {
    stopStream();
    onFinish?.call(
        Platform.isAndroid ? androidMax : max,
        Platform.isAndroid ? androidMin : min,
        calculateAverage(
            Platform.isAndroid ? androidAverageLux : cameraAverageLux));
  }

  void stopStream() {
    if (Platform.isAndroid) {
      GetBrightness.stopBrightnessStream();
    }
    _controller?.stopImageStream();
  }

  void dispose() {
    _controller?.dispose();
    _controller = null;
  }

  void reset() {
    _isPause = false;
    max = 0;
    min = 1037;
    currentAndroidData = 0;
    androidAverageLux.clear();
    androidMax = 0;
    androidMin = 1037;
    cameraAverageLux.clear();
    averageTemp.clear();
  }

  double calculateAverage(List<double> data) {
    if (data.isEmpty) {
      return 0.0;
    }
    data.sort();
    double ave = data.reduce((value, element) => value + element) / data.length;
    return ave;
  }

  Future<void> switchCamera() async {
    if (cameras.isNotEmpty) {
      CameraDescription? anotherName = cameras.firstWhereOrNull((element) =>
          element.lensDirection.name !=
          _controller?.description.lensDirection.name);
      if (anotherName?.lensDirection.name.isNotEmpty == true) {
        currentCamera = anotherName!;
        try {
          await _controller?.stopImageStream();
        } catch (e) {
          print(e);
        }
        await _controller?.dispose();
        _controller = null;
        _controller = CameraController(currentCamera!, ResolutionPreset.low,
            imageFormatGroup: ImageFormatGroup.yuv420);
        await _controller?.initialize();
      } else {
        EasyLoading.showToast("当前设备没有切换的其他相机");
      }
    } else {
      EasyLoading.showToast("当前设备没有可用的相机");
    }
  }

  void addFinishListener(onCheckFinish onFinish) {
    this.onFinish = onFinish;
  }

  void pause() {
    _isPause = true;
  }

  void resume() {
    _isPause = false;
  }

  void interrupt() {
    stopStream();
  }
}
